import * as _ from "lodash"
import { PageList } from "../data"
import httpClient from "../httpclient"

export enum RoleType {
  Primitive = "primitive",
  Predefined = "predefined",
  Custom = "custom"
}

export class Role {
  public id: string
  public name: string
  public authorities: string[] = []
  private store_id: string
  private staffs_count: number
  public description: string
  public type: RoleType

  public get storeId() {
    return this.store_id
  }

  public set storeId(storeId) {
    this.store_id = storeId
  }

  public get staffsCount() {
    return this.staffs_count
  }

}

class RoleQuery {
  private params = {}

  public page(page: number) {
    this.params["page"] = page
    return this
  }

  public limit(limit: number) {
    this.params["limit"] = limit
    return this
  }

  public storeId(storeId: string) {
    this.params["store_id"] = storeId
    return this
  }

  public list(): Promise<PageList<Role>> {
    return httpClient.get(`/v1/stores/${this.params["store_id"]}/roles`, { params: this.params })
      .then(({ data }) => {
        return _.assign(PageList.empty(), data, {
          elements: _.map(data.elements, element => _.assign(new Role(), element)),
        })
      })
  }
}

export class RoleServiceV1 {

  public static addRole(role: Role): Promise<Role> {
    return httpClient.post(`/v1/stores/${role.storeId}/roles`, role)
      .then(({ data }) => _.assign(new Role(), data))
  }

  public static getRole(storeId: string, roleId: string): Promise<Role> {
    return httpClient.get(`/v1/stores/${storeId}/roles/${roleId}`)
      .then(({ data }) => _.assign(new Role(), data))
  }

  public static getRoles(): RoleQuery {
    return new RoleQuery()
  }

  public static updateRole(role: Role): Promise<Role> {
    return httpClient.patch(`/v1/stores/${role.storeId}/roles/${role.id}`, role)
      .then(({ data }) => _.assign(new Role(), data))
  }

  public static deleteRole(storeId: string, roleId: string): Promise<void> {
    return httpClient.delete(`/v1/stores/${storeId}/roles/${roleId}`)
  }
}
